from datetime import datetime

from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from sqlalchemy.orm import load_only

from app import db
from cache.user import UserFollowingCache, UserCache
from models.user import Relation, User
from utils.decorators import login_required


class FollowUserResource(Resource):
    method_decorators = {'post': [login_required], 'get': [login_required]}

    def post(self):
        # 获取参数
        userid = g.userid
        parser = RequestParser()
        parser.add_argument('target', required=True, location='json', type=int)
        args = parser.parse_args()
        author_id = args.target

        # 获取当前时间
        update_time = datetime.now()

        # 查询数据
        relation = Relation.query.options(load_only(Relation.id)).filter(Relation.user_id == userid,
                                                                         Relation.author_id == author_id).first()

        if relation:  # 如果有, 修改记录
            relation.relation = Relation.RELATION.FOLLOW
            relation.update_time = datetime.now()

        else:  # 如果没有, 新增记录
            relation = Relation(user_id=userid, author_id=author_id, relation=Relation.RELATION.FOLLOW)
            db.session.add(relation)

        # 让作者的粉丝数量+1
        User.query.filter(User.id == author_id).update({'fans_count': User.fans_count + 1})
        # 让用户的关注数量+1
        User.query.filter(User.id == userid).update({'following_count': User.following_count + 1})

        db.session.commit()

        """更新缓存"""
        UserFollowingCache(userid).update(author_id, update_time.timestamp(), is_follow=True)

        # 返回结果
        return {'target': author_id}

    def get(self):
        """获取关注列表"""
        # 获取参数
        userid = g.userid
        parser = RequestParser()
        parser.add_argument('page', default=1, location='args', type=int)
        parser.add_argument('per_page', default=2, location='args', type=int)
        args = parser.parse_args()
        page = args.page
        per_page = args.per_page

        """查询数据 当前用户的关注列表"""

        following_list = UserFollowingCache(userid).get(page, per_page)

        author_list = []

        for author_id in following_list:
            author_cache = UserCache(author_id).get()

            # 此处暂不实现相互关注功能, 在下一小节中实现
            author_dict = {
                'id': author_cache['id'],
                'name': author_cache['name'],
                'photo': author_cache['photo'],
                'fans_count': author_cache['fans_count'],
                'mutual_follow': False
            }

            author_list.append(author_dict)

            # 获取用户关注数量
        user = UserCache(userid).get()

        # 返回数据
        return {'results': author_list, 'per_page': per_page, 'page': page, 'total_count': user['follow_count']}


class UnFollowUserResource(Resource):
    method_decorators = {'delete': [login_required]}

    def delete(self, target):
        # 获取参数
        userid = g.userid

        # 更新用户关系
        Relation.query.filter(Relation.user_id == userid, Relation.author_id == target,
                              Relation.relation == Relation.RELATION.FOLLOW).update(
            {'relation': 0, 'update_time': datetime.now()})

        # 让作者的粉丝数量-1
        User.query.filter(User.id == target).update({'fans_count': User.fans_count - 1})
        # 让用户的关注数量-1
        User.query.filter(User.id == userid).update({'following_count': User.following_count - 1})

        db.session.commit()

        """更新缓存"""
        UserFollowingCache(userid).update(target, is_follow=False)

        return {'target': target}
